Page({
  data: {
    isEdit: false,
    questionId: '',
    questionData: {
      title: '',
      type: '单选题',
      subject: '语文',
      difficulty: '中等',
      knowledge: '',
      options: [
        { id: 'A', content: '', isCorrect: false },
        { id: 'B', content: '', isCorrect: false },
        { id: 'C', content: '', isCorrect: false },
        { id: 'D', content: '', isCorrect: false }
      ],
      answer: '',
      analysis: ''
    },
    typeOptions: ['单选题', '多选题', '填空题', '解答题'],
    subjectOptions: ['语文', '数学', '英语'],
    difficultyOptions: ['简单', '中等', '困难']
  },

  onLoad: function(options) {
    if (options.id) {
      // 编辑现有题目
      this.setData({
        isEdit: true,
        questionId: options.id
      });
      this.loadQuestionData(options.id);
    }
  },

  // 加载试题数据
  loadQuestionData: function(questionId) {
    // 模拟从服务器加载数据
    // 实际应用中应调用云函数获取数据
    const mockData = {
      id: questionId,
      title: '下列词语中加点字的读音完全正确的一项是',
      type: '单选题',
      subject: '语文',
      difficulty: '中等',
      knowledge: '字音辨析',
      options: [
        { id: 'A', content: '勘(kān)探 轸(zhěn)念 熏陶(xūn)', isCorrect: true },
        { id: 'B', content: '倾(qǐng)斜 揣(chuǎi)测 蹊跷(qī)', isCorrect: false },
        { id: 'C', content: '咫(zhǐ)尺 梗(gěng)概 缄默(jiān)', isCorrect: false },
        { id: 'D', content: '沦(lún)陷 潜(qián)移 发酵(xiào)', isCorrect: false }
      ],
      answer: 'A',
      analysis: '正确选项是A，其中勘(kān)、轸(zhěn)、熏(xūn)的读音都是正确的。B项中"倾"应读作"qīng"，C项中"梗"应读作"gěn"，D项中"发酵"应读作"jiào"。'
    };
    
    setTimeout(() => {
      this.setData({
        questionData: mockData
      });
    }, 500);
  },

  // 处理输入变化
  handleInputChange: function(e) {
    const { field } = e.currentTarget.dataset;
    const value = e.detail.value;
    
    this.setData({
      [`questionData.${field}`]: value
    });
  },

  // 处理选项变化
  handleOptionChange: function(e) {
    const { index } = e.currentTarget.dataset;
    const value = e.detail.value;
    
    this.setData({
      [`questionData.options[${index}].content`]: value
    });
  },

  // 设置正确答案
  setCorrectOption: function(e) {
    const { index } = e.currentTarget.dataset;
    const { type, options } = this.data.questionData;
    
    if (type === '单选题') {
      // 单选题只能有一个正确答案
      const updatedOptions = options.map((option, idx) => {
        return {
          ...option,
          isCorrect: idx === index
        };
      });
      
      this.setData({
        'questionData.options': updatedOptions,
        'questionData.answer': options[index].id
      });
    } else if (type === '多选题') {
      // 多选题可以有多个正确答案
      const updatedOptions = [...options];
      updatedOptions[index].isCorrect = !updatedOptions[index].isCorrect;
      
      // 更新答案字符串
      const answer = updatedOptions
        .filter(opt => opt.isCorrect)
        .map(opt => opt.id)
        .join(',');
      
      this.setData({
        'questionData.options': updatedOptions,
        'questionData.answer': answer
      });
    }
  },

  // 添加选项
  addOption: function() {
    const { options } = this.data.questionData;
    const newOptionId = String.fromCharCode(65 + options.length); // A, B, C, ...
    
    this.setData({
      'questionData.options': [
        ...options,
        { id: newOptionId, content: '', isCorrect: false }
      ]
    });
  },

  // 删除选项
  removeOption: function(e) {
    const { index } = e.currentTarget.dataset;
    const { options } = this.data.questionData;
    
    if (options.length <= 2) {
      wx.showToast({
        title: '至少需要两个选项',
        icon: 'none'
      });
      return;
    }
    
    const updatedOptions = options.filter((_, idx) => idx !== index);
    
    // 重新分配选项ID
    const renamedOptions = updatedOptions.map((option, idx) => {
      return {
        ...option,
        id: String.fromCharCode(65 + idx)
      };
    });
    
    // 更新答案
    let answer = '';
    if (this.data.questionData.type === '单选题') {
      const correctOption = renamedOptions.find(opt => opt.isCorrect);
      answer = correctOption ? correctOption.id : '';
    } else if (this.data.questionData.type === '多选题') {
      answer = renamedOptions
        .filter(opt => opt.isCorrect)
        .map(opt => opt.id)
        .join(',');
    }
    
    this.setData({
      'questionData.options': renamedOptions,
      'questionData.answer': answer
    });
  },

  // 选择题型
  selectType: function(e) {
    const type = e.currentTarget.dataset.type;
    
    // 根据题型调整UI
    let options = this.data.questionData.options;
    let answer = this.data.questionData.answer;
    
    if (type === '填空题' || type === '解答题') {
      // 这些题型不需要选项
      options = [];
      answer = '';
    } else if (options.length === 0) {
      // 如果之前是填空题或解答题，现在切换到选择题，需要初始化选项
      options = [
        { id: 'A', content: '', isCorrect: false },
        { id: 'B', content: '', isCorrect: false },
        { id: 'C', content: '', isCorrect: false },
        { id: 'D', content: '', isCorrect: false }
      ];
    }
    
    this.setData({
      'questionData.type': type,
      'questionData.options': options,
      'questionData.answer': answer
    });
  },

  // 选择学科
  selectSubject: function(e) {
    const subject = e.currentTarget.dataset.subject;
    this.setData({
      'questionData.subject': subject
    });
  },

  // 选择难度
  selectDifficulty: function(e) {
    const difficulty = e.currentTarget.dataset.difficulty;
    this.setData({
      'questionData.difficulty': difficulty
    });
  },

  // 保存试题
  saveQuestion: function() {
    const { questionData, isEdit, questionId } = this.data;
    
    // 表单验证
    if (!questionData.title.trim()) {
      wx.showToast({
        title: '请输入题目内容',
        icon: 'none'
      });
      return;
    }
    
    // 验证选项和答案
    if (questionData.type === '单选题' || questionData.type === '多选题') {
      // 检查是否有空选项
      const hasEmptyOption = questionData.options.some(opt => !opt.content.trim());
      if (hasEmptyOption) {
        wx.showToast({
          title: '选项内容不能为空',
          icon: 'none'
        });
        return;
      }
      
      // 检查是否设置了正确答案
      const hasCorrectOption = questionData.options.some(opt => opt.isCorrect);
      if (!hasCorrectOption) {
        wx.showToast({
          title: '请设置正确答案',
          icon: 'none'
        });
        return;
      }
    } else if (questionData.type === '填空题' || questionData.type === '解答题') {
      if (!questionData.answer.trim()) {
        wx.showToast({
          title: '请填写参考答案',
          icon: 'none'
        });
        return;
      }
    }
    
    // 显示加载提示
    wx.showLoading({
      title: isEdit ? '正在更新...' : '正在保存...'
    });
    
    // 模拟保存过程
    // 实际应用中应调用云函数保存数据
    setTimeout(() => {
      wx.hideLoading();
      
      wx.showToast({
        title: isEdit ? '更新成功' : '保存成功',
        icon: 'success'
      });
      
      // 返回上一页
      setTimeout(() => {
        wx.navigateBack();
      }, 1000);
    }, 1500);
  },

  // 取消编辑
  cancelEdit: function() {
    wx.showModal({
      title: '确认取消',
      content: '未保存的内容将会丢失，确定取消吗？',
      success: (res) => {
        if (res.confirm) {
          wx.navigateBack();
        }
      }
    });
  }
}) 